<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :keyboard="false"
    :forceRender="true"
    v-bind:prefixNo="prefixNo"
    switchHelp
    switchFullscreen
    @cancel="handleCancel"
    wrapClassName="ant-modal-cust-warp"
    :id="prefixNo"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button @click="handleCancel">{{$t('inPrint.cancel')}}</a-button>
      <!-- <a-button v-if="isCanCheck" @click="handleOkAndCheck">{{$t('popup.saveReview')}}</a-button> -->
      <a-button type="primary" @click="handleOk" :disabled="submitBtnDisabled">{{$t('commodityManagement.preservation')}}</a-button>
    </template>
    <div style="position:absolute;bottom:53px;right:0;z-index:11" v-if="showRecover && !model.id">
      <span>{{ $t('popup.recoveryPrompt') }}</span>
      <a-button type="link" @click="recover" :disabled="submitBtnDisabled">{{$t('popup.recover')}}</a-button>
      <a-button type="link" @click="lose" :disabled="submitBtnDisabled">{{$t('popup.lose')}}</a-button>
    </div>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('basicInformation.customer')" data-step="1" :data-title="$t('basicInformation.customer')"
              :data-intro="$t('popup.customerMustUser')">
              <a-select :placeholder="$t('manuManagement.selectCustomer')" v-decorator="[ 'organId', validatorRules.organId ]"
                :dropdownMatchSelectWidth="false" showSearch optionFilterProp="children">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;"
                       @mousedown="e => e.preventDefault()" @click="addCustomer"><a-icon type="plus" /> {{$t('popup.newCustomers')}}</div>
                </div>
                <a-select-option v-for="(item,index) in cusList" :key="index" :value="item.id">
                  {{ item.supplier }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentDate')">
              <j-date v-decorator="['operTime', validatorRules.operTime]" :show-time="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.documentNo')" data-step="2" :data-title="$t('setailManagement.documentNo')"
              :data-intro="$t('popup.theDocumentOpened')">
              <a-input :placeholder="$t('setailManagement.pleaseEnterTheDocumentNumber')" v-decorator.trim="[ 'number',validatorRules.number  ]" :readOnly="true"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('salesManagement.operator')" data-step="3" :data-title="$t('salesManagement.operator')"
              :data-intro="$t('popup.theDataComesMenu')">
              <a-input :placeholder="$t('defaultTranslate.operator')" v-decorator.trim="['userName']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('otherJS.arrivalDate')">
              <j-date v-decorator="['arrivalTime']" :show-time="true" :placeholder="$t('otherJS.pleaseSelectTheArrDate')"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('otherJS.deliveryMethod')">
              <a-input :placeholder="$t('otherJS.pleaseEnterDeliveryMethod')" v-decorator.trim="[ 'deliveryMethod' ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator.trim="['creator']" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-item :labelCol="{xs: { span: 24 },sm: { span: 4 }}" :wrapperCol="{xs: { span: 24 },sm: { span: 20 }}" :label="$t('salesManagement.notesToDocuments')">
              <a-textarea :rows="1" :placeholder="$t('reportQuery.pleaseEnterComments')" v-decorator="[ 'remark' ]" style="margin-top:8px;"/>
            </a-form-item>
          </a-col>
        </a-row>
        <j-editable-table id="billModal"
          :key="newKey"
          :ref="refKeys[0]"
          :loading="materialTable.loading"
          :columns="materialTable.columns"
          :dataSource="materialTable.dataSource"
          :minWidth="minWidth"
          :maxHeight="300"
          :rowNumber="false"
          :rowSelection="true"
          :actionButton="true"
          :dragSort="true"
          :disabledRows="{id:disabledRowIds}"
          @valueChange="barCodeValueChange" 
          @inputPurchaseValueChange="onValueChange"
          @added="onAdded"
          @deleted="onDeleted">
          <template #buttonAfter>
            <a-row :gutter="24" style="float:left;" data-step="4" :data-title="$t('popup.codeScanningEntry')" :data-intro="$t('popup.thisSupportsGun')">
              <a-col v-if="scanStatus" :md="6" :sm="24">
                <a-button @click="scanEnter">{{$t('popup.codeScanningEntry')}}</a-button>
              </a-col>
              <a-col v-if="!scanStatus" :md="16" :sm="24" style="padding: 0 6px 0 12px">
                <a-input :placeholder="$t('popup.pleaseScanBarcode')" v-model="scanBarCode" @pressEnter="scanPressEnter" ref="scanBarCode"/>
              </a-col>
              <a-col v-if="!scanStatus" :md="6" :sm="24" style="padding: 0px">
                <a-button @click="stopScan">{{$t('popup.stowScanningCode')}}</a-button>
              </a-col>
            </a-row>
            <a-row :gutter="24" style="float:left;padding-bottom: 5px;">
              <a-col :md="24" :sm="24">
                <a-button style="margin-left: 8px" @click="handleHistoryBillList"><a-icon type="history" />{{$t('popup.historicalDocuments')}}</a-button>
              </a-col>
            </a-row>
          </template>
          <template #delete="record">
            <div style="text-align: center;">
              <a-popconfirm :title="$t('manuManagement.areDelete')"
                @confirm="() => removeRows(record)">
                <a-icon type="delete"></a-icon>
              </a-popconfirm>
            </div>
          </template>
          <template #rowIndex="record">
            <div style="text-align: center;">{{ record.index + 1 }}</div>
          </template>
        </j-editable-table>
        
        <a-row class="form-row" :gutter="24">
          <!-- <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.preferentialRate')" data-step="5" :data-title="$t('inPrint.preferentialRate')"
                         :data-intro="$t('popup.proportionDiscount')">
              <a-input style="width:185px;" :placeholder="$t('popup.pleaseDiscountRate')" v-decorator.trim="[ 'discount' ]" suffix="%" @keyup="onKeyUpDiscount"/>
            </a-form-item>
          </a-col> -->
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.paymentPreference')"
              data-step="6" :data-title="$t('inPrint.paymentPreference')" :data-intro="$t('popup.theAmountGoods')">
              <a-input :placeholder="$t('popup.pleasePaymentPreference')" v-decorator.trim="['discountMoney']"
                @keyup="onKeyUpDiscountMoney" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" v-show="false">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('inPrint.amountAfter')" data-step="7"
              :data-title="$t('inPrint.amountAfter')" :data-intro="$t('popup.amountAmountGoodsIn')">
              <a-input :placeholder="$t('popup.pleaseEnterAfterDiscount')" v-decorator.trim="['discountLastMoney']"
                :readOnly="true" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24"></a-col>
        </a-row>
        <a-row class="form-row" :gutter="24" v-show="false">
          <!-- <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('setailManagement.settlementAccount')"
              data-step="9" :data-title="$t('setailManagement.settlementAccount')"
              :data-intro="$t('popup.ifMultipleAreBox')">
              <a-select style="width:185px;" :placeholder="$t('popup.selectSettlementAccount')"
                v-decorator="['accountId']" :dropdownMatchSelectWidth="false" allowClear @select="selectAccount">
                <div slot="dropdownRender" slot-scope="menu">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0;" />
                  <div v-if="isTenant" style="padding: 4px 8px; cursor: pointer;" @mousedown="e => e.preventDefault()"
                    @click="addAccount"><a-icon type="plus" /> {{ $t('popup.newAccount') }}</div>
                </div>
                <a-select-option v-for="(item, index) in accountList" :key="index" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
              <a-tooltip :title="$t('popup.multiAccountDetails')">
                <a-button type="default" icon="folder" style="margin-left: 8px;" size="small"
                  v-show="manyAccountBtnStatus" @click="handleManyAccount" />
              </a-tooltip>
            </a-form-item>
          </a-col> -->
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('manuManagement.payDeposit')">
              <a-input :placeholder="$t('popup.pleaseEnterPaymentDeposit')"
                v-decorator.trim="['changeAmount', validatorRules.price]" @keyup="onKeyUpChangeAmount" />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
          </a-col>
          <a-col :lg="6" :md="12" :sm="24">
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="24">
          <a-col :lg="6" :md="12" :sm="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('popup.enclosure')" data-step="8" :data-title="$t('popup.enclosure')" :data-intro="$t('popup.youUploadPictures')">
              <div v-if="fileLoading">Loading...</div>
              <j-upload v-else :fileList="fileList" bizPath="bill"></j-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <many-account-modal ref="manyAccountModalForm" @ok="manyAccountModalFormOk"></many-account-modal>
    <customer-modal ref="customerModalForm" @ok="customerModalFormOk"></customer-modal>
    <account-modal ref="accountModalForm" @ok="accountModalFormOk"></account-modal>
    <history-bill-list ref="historyBillListModalForm"></history-bill-list>
  </j-modal>
</template>
<script>
  import pick from 'lodash.pick'
  import ManyAccountModal from '../dialog/ManyAccountModal'
  import CustomerModal from '../../system/modules/CustomerModal'
  import AccountModal from '../../system/modules/AccountModal'
  import HistoryBillList from '../dialog/HistoryBillList'
  import { FormTypes } from '@/utils/JEditableTableUtil'
  import { JEditableTableMixin } from '@/mixins/JEditableTableMixin'
  import { BillModalMixin } from '../mixins/BillModalMixin'
  import { getMpListShort,handleIntroJs } from "@/utils/util"
  import JSelectMultiple from '@/components/jeecg/JSelectMultiple'
  import JUpload from '@/components/jeecg/JUpload'
  import JDate from '@/components/jeecg/JDate'
  import Vue from 'vue'
  export default {
    name: "DirectOrderModal",
    mixins: [JEditableTableMixin, BillModalMixin],
    components: {
      ManyAccountModal,
      CustomerModal,
      AccountModal,
      HistoryBillList,
      JUpload,
      JDate,
      JSelectMultiple,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
    },
    data () {
      return {
        title:this.$t('manuManagement.directOrdersFromManufacturers'),
        newKey:'',
        width: '1600px',
        moreStatus: false,
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        visible: false,
        operTimeStr: '',
        promotionOrderType:3,//促销活动类型
        prefixNo: 'CJZF',
        fileList:[],
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        refKeys: ['materialDataTable', ],
        activeKey: 'materialDataTable',
        materialTable: {
          loading: false,
          dataSource: [],
          columns: [
            { title: this.$t('commodityManagement.delete'), width: '3%', key: 'delete', type: 'slot' },
            { title: this.$t('defaultTranslate.lineNumber'), key: 'rowIndex', width: '4%', type: 'slot' },
            { title: this.$t('otherJS.goodsId'), key: 'materialId', width: '7%', type: FormTypes.hidden },
            // { title: this.$t('setailManagement.warehouseName'), key: 'depotId', width: '5%', type: FormTypes.hidden },
            // { title: this.$t('reportQuery.barcode'), key: 'barCode', width: '8%', type: FormTypes.popupJsh, kind: 'material', multi: true,
            //   // validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            // },
            { title: this.$t('otherJS.goodsId'), key: 'meId', width: '6%', type: FormTypes.hidden },
            { title: this.$t('otherJS.productName'), width: '250px', key: 'name',type: FormTypes.popupJsh, kind: 'material', multi: true, placeholder: this.$t('otherJS.productName') },
            { title: this.$t('reportQuery.specification'), key: 'standard', width: '120px', type: FormTypes.input,readonly:true },
            { title: this.$t('reportQuery.category'), key: 'categoryName', width: '6%', type: FormTypes.input,readonly:true  },
            { title: this.$t('reportQuery.model'), key: 'model', width: '120px', type: FormTypes.input,readonly:true },
            { title: this.$t('reportQuery.color'), key: 'color', width: '120px', type: FormTypes.input,readonly:true },
            // { title: this.$t('reportQuery.extendedInformation'), key: 'materialOther', width: '5%', type: FormTypes.input,readonly:true },
            { title: this.$t('reportQuery.inventory'), key: 'stock', width: '120px', type: FormTypes.input,readonly:true },
            { title: this.$t('reportQuery.unit'), key: 'unit', width: '140px', type: FormTypes.input,readonly:true },
            { title: this.$t('commodityManagement.multiAttribute'), key: 'sku', width: '120px', type: FormTypes.input,readonly:true },
            { title: this.$t('reportQuery.quantity'), key: 'operNumber', width: '180px', type: FormTypes.inputNumber, statistics: true,
              validateRules: [{ required: true, message: '${title}'+this.$t('inPrint.cannotTe') }]
            },
            { title: this.$t('reportQuery.unitPrice') , key: 'unitPrice', width: '150px', type: FormTypes.inputNumber,
              validateRules: [{handler:this.validateCheckNumber, message: '${title}' }]
             },
            // 过滤赠品
            { title: this.$t('reportQuery.unitPrice'), key: 'priceNote', width: '0', type: FormTypes.hidden},
            { title: '', key: 'sourceId', width: '0', type: FormTypes.normal },
            // sourceId 传值
            { title: '', key: 'custom4', width: '0', type: FormTypes.normal },
            { title: '123', key: 'custom8', width: '5%', type: FormTypes.hidden },
            
            { title: this.$t('basicInformation.taxRate'), key: 'taxRate', width: '120px', type: FormTypes.inputNumber,placeholder: '%'},
            { title: this.$t('inPrint.taxAmount'), key: 'taxMoney', width: '120px', type: FormTypes.inputNumber, readonly: true, statistics: true },
            { title: this.$t('inPrint.taxUnitPrice'), key: 'taxUnitPrice', width: '120px', type: FormTypes.inputNumber, readonly: true, statistics: true },
            { title: this.$t('inPrint.totalTax'), key: 'taxLastMoney', width: '120px', type: FormTypes.hidden, statistics: true },
            { title: this.$t('financialManagement.remarks'), key: 'remark', width: '150px', type: FormTypes.input },
            { title: this.$t('popup.defaultSupplier'), key: 'organName', width: '180px',readonly: true, placeholder: this.$t('popup.defaultSupplier'),type: FormTypes.input},
            { title: this.$t('reportQuery.amount'), key: 'allPrice', width: '150px', type: FormTypes.inputNumber, statistics: true,readonly: true },
            { title: '', key: 'organId', width: '0',placeholder: this.$t('popup.defaultSupplier'),type: FormTypes.hidden},
          ]
        }, 
        confirmLoading: false,
        validatorRules:{
          operTime:{
            rules: [
              { required: true, message: this.$t('popup.pleaseEnterDocumentDate')+'!' }
            ]
          },
          organId:{
            rules: [
              { required: true, message: this.$t('popup.pleaseSelectCustomer')+'!' }
            ]
          },
          number:{
            rules: [
              { required: true, message: this.$t('otherJS.DocumentNoFailure') }
            ]
          }
        },
        url: {
          add: '/depotHead/addDepotHeadAndDetail',
          edit: '/depotHead/updateDepotHeadAndDetail',
          detailList: '/depotItem/getDetailList'
        }
      }
    },
    
  provide(){
    return {
      getConfig: ()=>{
        return {enableBatchNumber:'1'}
      }
    }
  },
    created () {
      
    },
    methods: {
      //调用完edit()方法之后会自动调用此方法
      editAfter() {
        console.log('editAfter :>> ', 'editAfter');
        this.arrList = []
        this.billStatus = '0'
        this.changeColumnHide()
        if (this.action === 'add') {
          this.addInit(this.prefixNo)
          this.personList.value = ''
          this.fileList = []
          this.$nextTick(() => {
            handleIntroJs(this.prefixNo, 1)
          })
        } else {
          this.model.operTime = this.model.operTimeStr
          if(this.model.accountId == null) {
            this.model.accountId = 0
            this.manyAccountBtnStatus = true
            this.accountIdList = this.model.accountIdList
            this.accountMoneyList = this.model.accountMoneyList
          } else {
            this.manyAccountBtnStatus = false
          }
          this.personList.value = this.model.salesMan
          
          this.$nextTick(() => {
            this.form.setFieldsValue(pick(this.model,'organId', 'deliveryMethod', 'arrivalTime', 'operTime', 'number', 'remark',
              'discount','discountMoney','discountLastMoney','accountId','changeAmount','salesMan'))
          });
          // 加载子表数据
          let params = {
            headerId: this.model.id,
            mpList: getMpListShort(Vue.ls.get('materialPropertyList'))  //扩展属性
          }
          let url = this.readOnly ? this.url.detailList : this.url.detailList;
          this.requestSubTableData(url, params, this.materialTable);
          let arr = []
          this.materialTable.dataSource.forEach(item => {
            arr.push(item.materialId)
          });
          this.materialIds = arr.toString()
          this.changeMaterialIds()
          
        }
        //复制新增单据-初始化单号和日期
        if(this.action === 'copyAdd') {
          this.model.id = ''
          this.model.tenantId = ''
          this.copyAddInit(this.prefixNo)
        }
        this.initCustomer()
        this.initSalesman()
        // this.initAccount()
      },
      //提交单据时整理成formData
      classifyIntoFormData(allValues) {
        let totalPrice = 0
        let billMain = Object.assign(this.model, allValues.formValue)
        let detailArr = allValues.tablesValue[0].values
        billMain.type = '其它'
        billMain.subType = '厂家直发'
        billMain.defaultNumber = billMain.number
        for(let item of detailArr){
          item.depotId = '' //订单不需要仓库
          totalPrice += item.allPrice-0
          item.discountPrice = item.custom8 //折前单价
          item.discountAllPrice = this.$toDecimal(item.operNumber * (item.custom8  - item.unitPrice ))//折扣额
        }
        billMain.totalPrice = totalPrice
        if(billMain.accountId === 0) {
          billMain.accountId = ''
        }
        billMain.accountIdList = this.accountIdList.length>0 ? JSON.stringify(this.accountIdList) : ""
        billMain.accountMoneyList = this.accountMoneyList.length>0 ? JSON.stringify(this.accountMoneyList) : ""
        // if(this.fileList && this.fileList.length > 0) {
        //   billMain.fileName = this.fileList
        // } else {
        //   billMain.fileName = ''
        // }
        if(this.model.id){
          billMain.id = this.model.id
        }
        billMain.salesMan = this.personList.value
        billMain.status = this.billStatus
        if(!this.model.id){
        // 新增默认未报价
          billMain.quotationStatus = '0'
        }
        let fileList = JSON.stringify(JSON.parse(localStorage.getItem("fileList")))
        return {
          info: JSON.stringify(billMain),
          attachment: fileList,
          rows: JSON.stringify(detailArr),
        }
      },
      handleHistoryBillList() {
        let organId = this.form.getFieldValue('organId')
        this.$refs.historyBillListModalForm.show(this.$t('manuManagement.other'),this.$t('manuManagement.salesOrder'), this.$t('manuManagement.customer'), organId);
        this.$refs.historyBillListModalForm.disableSubmit = false;
      },
      removeRows (text) {
        this.$refs[this.refKeys[0]].removeRows(text.rowId)
      }
    }
  }
</script>
<style scoped lang="less">
::v-deep .ant-spin-container .thead {
  background: #beddf9;
  & > .tr > .td {
    border-left: 1px solid #f2f2f2;
    text-align: center;
  }
}
</style>